package com.yc.cloud.common.oss.utils;

import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class VideoUtils {

    private static Process process;
    private static final String FFMPEG_PATH = "ffmpeg";

    /**
     * 生成视频封面照片
     *
     * @param path 视频文件路径
     * @return
     */
    public static boolean generateCover(String path, String coverPath) {
        List<String> commands = new ArrayList<>();
        commands.add(FFMPEG_PATH);
        commands.add("-y");
        commands.add("-i");
        commands.add(path);
        commands.add("-ss");
        commands.add("00:00:01");
        commands.add("-vframes");
        commands.add("1");
        commands.add(coverPath);
        return processCommands(commands);
    }

    private static boolean processCommands(List<String> commands) {
        // System.out.println("commands=" + commands.replaceAll(",", ""););
        val stringBuilder = new StringBuilder();
        for (String command : commands) {
            stringBuilder.append(command).append(" ");
        }
        log.info(stringBuilder.toString());
        ProcessBuilder builder = new ProcessBuilder();
        builder.command(commands);
        return processOperation(builder);
    }

    private static boolean processOperation(ProcessBuilder builder) {
        InputStream error = null;
        InputStream is = null;
        try {
            process = builder.start();
            //process.waitFor();//等待进程执行完毕
            //防止ffmpeg进程塞满缓存造成死锁
            error = process.getErrorStream();
            is = process.getInputStream();
            byte[] b = new byte[1024];
            int readbytes = -1;
            while ((readbytes = error.read(b)) != -1) {
                System.out.println("FFMPEG视频转换进程错误信息：" + new String(b, 0, readbytes));
                // return  false;
            }
            while ((readbytes = is.read(b)) != -1) {
                System.out.println("FFMPEG视频信息：" + new String(b, 0, readbytes));
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (error != null) {
                    error.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    public static void main(String[] args) {
        generateCover("/Users/jackgu/Documents/mydata/xrhub/admin/1722826649133.mp4", "/Users/jackgu/Documents/mydata/xrhub/admin/1722826649133_cover.jpg");
    }
}
